package services

import (
	"app/common/constant"
	"app/internal/structs/responses"
	fileTools "app/pkg/file"
	"app/pkg/oss"
	"bytes"
	"io/ioutil"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/h2non/filetype"
)

// @Summary	单文件上传
// @Schemes
// @Description	单文件上传 /manager/common/file/upload
// @Tags			公共接口
// @Acappt			mpfd
// @Param			Authorization	header		string												true	"签名"
// @Param			file			formData	file												true	"文件内容"
// @success		200				{object}	response.JSONResult{data=model.SingleFileResponse}	"desc"
// @Router			/manager/common/file/upload [POST]
func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	// bucket := oss.NewQnOss()
	src, _ := file.Open()
	buf, _ := ioutil.ReadAll(src)
	if filetype.IsImage(buf) || filetype.IsVideo(buf) {
		ext := fileTools.GetExt(file.Filename)
		dstName := fileTools.DstName("img", ext)
		if dstName == "" {
			c.JSON(http.StatusOK, constant.ErrInfo{Code: constant.LogicError, Msg: "保存文件失败"})
			return
		}

		// //上传文件
		// if err := bucket.PutImageBytes(dstName, buf); err != nil {
		// 	log.NewError(c.GetString("requestId"), "putObject failed", err)
		// 	c.JSON(http.StatusOK, constant.ErrInfo{Code: constant.LogicError, Msg: "上传文件失败"})
		// 	return
		// }
		// qn := oss.NewQnOss()
		// //上传文件
		// if err = qn.PutImageBytes(dstName, byt); err != nil {
		// 	return
		// }
		bucket, _ := oss.DefaultBucket()
		//上传文件
		err := bucket.PutObject(dstName, bytes.NewReader(buf))
		if err != nil {
			return
		}
		// fileInfo, _ := os.Stat(pathName)
		fileResponse := responses.SingleFileResponse{}
		fileResponse.Path = dstName
		fileResponse.Size = int64(len(buf))
		fileResponse.Url = oss.NewAliOss().PreviewFileUrl(dstName)
		// fileResponse.ThumbUrl = oss.NewAliOss().PreviewUrl(dstName, 200, 0)
		c.JSON(http.StatusOK, gin.H{"code": constant.NoError, "msg": "", "data": fileResponse})
	} else {
		c.JSON(http.StatusOK, constant.ErrInfo{Code: constant.LogicError, Msg: "文件类型错误"})
		return
	}
}

// @Summary	单文件上传
// @Schemes
// @Description	单文件上传 /api/common/file/upload
// @Tags			公共接口
// @Acappt			mpfd
// @Param			file			formData	file												true	"文件内容"
// @success		200				{object}	response.JSONResult{data=model.SingleFileResponse}	"desc"
// @Router			/api/common/file/upload [POST]
func CommUpload(c *gin.Context) {
	Upload(c)
}
